package com.csg.web.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author george
 */
@ServerEndpoint("/ws")
@Component
@Slf4j
public class WebSocketServer {

    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        log.info("有客户端连接：{}", session.getId());
        clients.put(session.getId(), session);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("有客户端断开：{}", session.getId());
        clients.remove(session.getId());
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("服务器收到客户端消息：{}", message);
        sendAll(message);
    }

    private void sendAll(String message) {
        clients.values().forEach(session -> session.getAsyncRemote().sendText(message));
    }
}
